package engine.logic
{
	import engine.data.ModelLocator;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class ServerTimerLogic
	{
		private var _model:ModelLocator;
		private static var _self:ServerTimerLogic;
		private var _timer:Timer;
		private var _serverTimer:Number;
		private var _timeData:Date;
		private var _index:int	=	0;
		public function ServerTimerLogic()
		{
			init();
		}
		public static function getInstance():ServerTimerLogic
		{
			if(_self	==	null)
			{
				_self	=	new ServerTimerLogic();
			}
			return _self;
		}
		private function init():void
		{
			_timer	=	new Timer(1000);
			_model	=	ModelLocator.getInstance();
			_timer.addEventListener(TimerEvent.TIMER,	timerHandle);
			
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_SENDSERVERTIME),showServerTimerHandle);
			
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_QUERYSERVERTIME);
		}
		/**
		 * 返回服务器时间
		 * @param e
		 * 
		 */		
		private function showServerTimerHandle(e:CustomMsgEvent):void
		{
			_serverTimer	=	e.pList[0];
			_timer.stop();
			_timer.start();
//			_model.removeEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_SENDSERVERTIME),showServerTimerHandle);
			
		}
		/**
		 * 自行计算服务器时间 
		 * @param e
		 * 
		 */		
		private function timerHandle(e:TimerEvent):void
		{
			_serverTimer ++;
			_index++;
//			trace("serverTime=" + _serverTimer);
			if(_index > 30)
			{
				_index	=	0;
				_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_SENDSERVERTIME),showServerTimerHandle);
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_QUERYSERVERTIME);
			}
		}
		/**
		 * 返回时间 
		 * @return 
		 * 
		 */		
		public function getServerTimer():Number
		{
			return _serverTimer;
		}
		
	}
}